package com.yubest.seatastock.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Map;

@Service
public class StockService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Transactional
    public Boolean sub(Integer skuId, Integer stock) {
        Map<String, Object> map = jdbcTemplate.queryForMap(MessageFormat.format("select * from t_stock where sku_id = {0}", skuId));
        if (!map.containsKey("id")) {
            return false;
        }
        Integer myStock = (Integer) map.get("stock");
        if (myStock < stock) {
            return false;
        }
        jdbcTemplate.update(MessageFormat.format("update t_stock set stock = stock - {0} where sku_id = {1}", stock, skuId));
        return true;
    }
}
